package com.wang.example.netty.codec.custom;

import com.alibaba.fastjson.JSON;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import io.netty.util.CharsetUtil;

/**
 * @author suzhe
 * @date 2019/1/27
 */
public class JsonEncoder extends MessageToByteEncoder<User> {

    @Override
    protected void encode(ChannelHandlerContext ctx, User msg, ByteBuf out) throws Exception {
        System.out.println("JsonEncoder:"+msg);
        String userJson = JSON.toJSONString(msg);
        //将消息写入ByteBuf中
        out.writeBytes(userJson.getBytes(CharsetUtil.UTF_8));
    }

}
